<?php
/*
Plugin Name: Markdown Batch Import
Plugin URI: https://github.com/yourusername/markdown-import
Description: 批量导入Markdown文件到WordPress，支持分类、标签和自定义日期
Version: 1.1
Author: Your Name
License: GPL v2 or later
*/

// 防止直接访问
if (!defined('ABSPATH')) {
    exit;
}

// 在文件开头添加引入 Prism 资源的函数
function markdown_import_enqueue_scripts() {
    wp_enqueue_style('prism', 'https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism.min.css');
    wp_enqueue_script('prism', 'https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/prism.min.js', array(), '1.29.0', true);
    wp_enqueue_script('prism-autoloader', 'https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/plugins/autoloader/prism-autoloader.min.js', array('prism'), '1.29.0', true);
}
add_action('wp_enqueue_scripts', 'markdown_import_enqueue_scripts');

// 添加管理菜单
function markdown_import_menu() {
    add_menu_page(
        '导入Markdown', 
        'Markdown导入',
        'manage_options',
        'markdown-import',
        'markdown_import_page',
        'dashicons-upload'
    );
}
add_action('admin_menu', 'markdown_import_menu');

// 更新导入页面
function markdown_import_page() {
    ?>
    <div class="wrap">
        <h1>Markdown批量导入</h1>
        <form method="post" enctype="multipart/form-data">
            <table class="form-table">
                <tr>
                    <th scope="row">选择Markdown文件</th>
                    <td>
                        <input type="file" name="markdown_files[]" multiple accept=".md,.markdown" required>
                    </td>
                </tr>
                <tr>
                    <th scope="row">文章状态</th>
                    <td>
                        <select name="post_status">
                            <option value="publish">立即发布</option>
                            <option value="draft">保存为草稿</option>
                            <option value="private">私密发布</option>
                        </select>
                    </td>
                </tr>
                <tr>
                    <th scope="row">分类</th>
                    <td>
                        <?php
                        $categories = get_categories(array('hide_empty' => false));
                        foreach ($categories as $category) {
                            echo '<label><input type="checkbox" name="post_categories[]" value="' . $category->term_id . '"> ' . $category->name . '</label><br>';
                        }
                        ?>
                    </td>
                </tr>
                <tr>
                    <th scope="row">标签</th>
                    <td>
                        <input type="text" name="post_tags" class="regular-text" placeholder="用逗号分隔多个标签">
                    </td>
                </tr>
                <tr>
                    <th scope="row">发布日期</th>
                    <td>
                        <select name="date_option">
                            <option value="current">使用当前时间</option>
                            <option value="file">使用文件修改时间</option>
                            <option value="custom">自定义时间</option>
                        </select>
                        <div id="custom_date" style="display:none; margin-top: 10px;">
                            <input type="datetime-local" name="custom_date_value">
                        </div>
                    </td>
                </tr>
            </table>
            <?php wp_nonce_field('markdown_import_action', 'markdown_import_nonce'); ?>
            <p class="submit">
                <input type="submit" name="submit" class="button button-primary" value="开始导入">
            </p>
        </form>
    </div>

    <script>
    jQuery(document).ready(function($) {
        $('select[name="date_option"]').change(function() {
            if ($(this).val() === 'custom') {
                $('#custom_date').show();
            } else {
                $('#custom_date').hide();
            }
        });
    });
    </script>
    <?php

    if (isset($_POST['submit']) && check_admin_referer('markdown_import_action', 'markdown_import_nonce')) {
        handle_markdown_import();
    }
}

// 更新处理导入逻辑
function handle_markdown_import() {
    if (!class_exists('Parsedown')) {
        require_once plugin_dir_path(__FILE__) . 'vendor/Parsedown.php';
    }
    
    $parsedown = new Parsedown();
    $files = $_FILES['markdown_files'];
    $post_status = $_POST['post_status'];
    $post_categories = isset($_POST['post_categories']) ? $_POST['post_categories'] : array();
    $post_tags = !empty($_POST['post_tags']) ? explode(',', $_POST['post_tags']) : array();
    $date_option = $_POST['date_option'];
    $custom_date = isset($_POST['custom_date_value']) ? $_POST['custom_date_value'] : '';
    
    $success_count = 0;
    $error_count = 0;

    for ($i = 0; $i < count($files['name']); $i++) {
        if ($files['error'][$i] === UPLOAD_ERR_OK) {
            $content = file_get_contents($files['tmp_name'][$i]);
            $filename = pathinfo($files['name'][$i], PATHINFO_FILENAME);
            
            // 解析Markdown元数据
            $metadata = parse_markdown_metadata($content);
            $content = $metadata['content'];
            
            // 转换Markdown为HTML
            $html_content = $parsedown->text($content);
            
            // 设置发布日期
            $post_date = '';
            switch ($date_option) {
                case 'current':
                    $post_date = current_time('mysql');
                    break;
                case 'file':
                    $post_date = date('Y-m-d H:i:s', filemtime($files['tmp_name'][$i]));
                    break;
                case 'custom':
                    $post_date = date('Y-m-d H:i:s', strtotime($custom_date));
                    break;
            }
            
            // 创建文章
            $post_data = array(
                'post_title'    => !empty($metadata['title']) ? $metadata['title'] : $filename,
                'post_content'  => $html_content,
                'post_status'   => $post_status,
                'post_author'   => get_current_user_id(),
                'post_type'     => 'post',
                'post_date'     => $post_date,
                'post_date_gmt' => get_gmt_from_date($post_date)
            );
            
            $post_id = wp_insert_post($post_data);
            
            if ($post_id) {
                // 设置分类（合并表单选择的分类和元数据中的分类）
                $categories = $post_categories;
                if (!empty($metadata['categories'])) {
                    foreach ($metadata['categories'] as $cat_name) {
                        $cat = get_category_by_slug(sanitize_title($cat_name));
                        if (!$cat) {
                            // 如果分类不存在，创建新分类
                            $cat_id = wp_create_category($cat_name);
                            if ($cat_id) {
                                $categories[] = $cat_id;
                            }
                        } else {
                            $categories[] = $cat->term_id;
                        }
                    }
                }
                if (!empty($categories)) {
                    wp_set_post_categories($post_id, array_unique($categories));
                }
                
                // 设置标签（合并表单输入的标签和元数据中的标签）
                $tags = $post_tags;
                if (!empty($metadata['tags'])) {
                    $tags = array_merge($tags, $metadata['tags']);
                }
                if (!empty($tags)) {
                    wp_set_post_tags($post_id, array_unique($tags));
                }
                
                // 处理特色图片
                if (!empty($metadata['featured_image'])) {
                    handle_featured_image($post_id, $metadata['featured_image']);
                }
                
                $success_count++;
            } else {
                $error_count++;
            }
        }
    }
    
    echo '<div class="notice notice-success"><p>导入完成！成功：' . $success_count . '，失败：' . $error_count . '</p></div>';
}

// 解析Markdown元数据
function parse_markdown_metadata($content) {
    $metadata = array(
        'title' => '',
        'featured_image' => '',
        'categories' => array(),
        'tags' => array(),
        'content' => $content
    );
    
    // 检查是否存在元数据
    if (preg_match('/^---\s*\n(.*?)\n---\s*\n(.*)/s', $content, $matches)) {
        $metadata['content'] = $matches[2];
        
        // 解析元数据
        foreach (explode("\n", $matches[1]) as $line) {
            // 处理title=格式
            if (preg_match('/^title=(.*)$/', $line, $title_match)) {
                $metadata['title'] = trim($title_match[1]);
                continue;
            }
            
            // 处理categories=格式
            if (preg_match('/^categories=(.*)$/', $line, $cat_match)) {
                $metadata['categories'] = array_map('trim', explode(',', $cat_match[1]));
                continue;
            }
            
            // 处理tags=格式
            if (preg_match('/^tags=(.*)$/', $line, $tag_match)) {
                $metadata['tags'] = array_map('trim', explode(',', $tag_match[1]));
                continue;
            }
            
            // 处理YAML格式
            if (preg_match('/^(\w+):\s*(.*)$/', $line, $kv)) {
                $metadata[$kv[1]] = trim($kv[2]);
            }
        }
    }
    
    return $metadata;
}

// 处理特色图片
function handle_featured_image($post_id, $image_url) {
    require_once(ABSPATH . 'wp-admin/includes/media.php');
    require_once(ABSPATH . 'wp-admin/includes/file.php');
    require_once(ABSPATH . 'wp-admin/includes/image.php');
    
    // 下载图片
    $tmp = download_url($image_url);
    
    if (!is_wp_error($tmp)) {
        $file_array = array(
            'name' => basename($image_url),
            'tmp_name' => $tmp
        );
        
        // 上传到媒体库
        $attachment_id = media_handle_sideload($file_array, $post_id);
        
        if (!is_wp_error($attachment_id)) {
            set_post_thumbnail($post_id, $attachment_id);
        }
        
        @unlink($tmp);
    }
}